<template>
  <div>
    <van-address-edit
      :area-list="areaList"
      show-set-default
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      :address-info="addressInfo"
    />
  </div>
</template>

<script>
import areaList from "../../plugins/area";
export default {
  data() {
    return {
      areaList,
      address: [],
      addressInfo: {}
    };
  },
  created() {
    this.getAddressList();
    if (this.$store.state.status === "edit") {
      const addressId = location.hash.split("=")[1];
      // console.log(addressId);
      const editAddress = this.address.filter(item => item.id == addressId);
      // console.log(editAddress);
      this.addressInfo = editAddress[0];
    }
  },
  methods: {
    getAddressList() {
      if (localStorage.getItem("address") == null) return false;
      this.address = JSON.parse(localStorage.getItem("address"));
    },
    onSave(content) {
      if (!content.id) {
        content.id = Math.random()
          .toString()
          .replace(".", "");
        this.address.push(content);
        console.log(this.address);
        this.$toast.success("地址保存成功！");
      }
      // console.log(content);
      this.address.some(item => {
        if (item.id === content.id) {
          item.name = content.name;
          item.tel = content.tel;
          item.areaCode = content.areaCode;
          item.addressDetail = content.addressDetail;
          item.isDefault = content.isDefault;
        }
        return;
      });
      localStorage.setItem("address", JSON.stringify(this.address));
      this.$toast.success("地址修改成功！");
      this.$router.push("/address_list");
    }
  }
};
</script>

<style lang="less" scoped>
</style>